package com.reebake.ideal.user.controller.client;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.user.client.UserThirdPartyClient;
import com.reebake.ideal.user.entity.UserThirdPartyDTO;
import com.reebake.ideal.user.entity.UserThirdParty;
import com.reebake.ideal.user.service.UserThirdPartyService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
@RequestMapping("/client/user/third/party")
public class UserThirdPartyClientController implements UserThirdPartyClient {
    private final UserThirdPartyService userThirdPartyService;

    private UserThirdParty query(String source, String uuid) {
        LambdaQueryWrapper<UserThirdParty> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserThirdParty::getSource, source).eq(UserThirdParty::getUuid, uuid);

        return userThirdPartyService.getOne(queryWrapper);
    }

    @Override
    public void saveOrUpdate(UserThirdPartyDTO userThirdPartyDTO) {
        String uuid = userThirdPartyDTO.getUuid();
        String source = userThirdPartyDTO.getSource();
        UserThirdParty entity = BeanUtil.copyProperties(userThirdPartyDTO, UserThirdParty.class);

        UserThirdParty existsOne = query(source, uuid);
        if(ObjectUtil.isNotNull(existsOne)) {
            entity.setUserThirdPartyId(existsOne.getUserThirdPartyId());
        }

        userThirdPartyService.saveOrUpdate(entity);
    }
}
